import os
from PyQt5.QtCore import QFile, QTextStream, QObject

class ThemeManager(QObject):
    """主题管理器"""
    
    def __init__(self):
        super().__init__()
        self.themes = {
            'dark': 'resources/styles/dark_theme.qss',
            'light': 'resources/styles/light_theme.qss'
        }
        self.current_theme = 'dark'
    
    def get_resource_path(self, relative_path):
        """获取资源文件的绝对路径，支持打包后的资源访问"""
        # 首先尝试从当前工作目录查找
        base_path = os.path.dirname(os.path.abspath(__file__))
        resource_path = os.path.join(base_path, "..", "resources", relative_path)
        
        if os.path.exists(resource_path):
            return resource_path
        
        # 如果找不到，尝试从打包后的资源目录查找
        resource_path = os.path.join("resources", relative_path)
        if os.path.exists(resource_path):
            return resource_path
        
        # 如果都找不到，返回原始路径（打包工具可能会处理）
        return os.path.join("resources", relative_path)
    
    def load_theme(self, theme_name):
        """加载指定主题"""
        if theme_name not in self.themes:
            print(f"主题 '{theme_name}' 不存在")
            return None
        
        theme_path = self.get_resource_path(f"styles/{theme_name}_theme.qss")
        if not os.path.exists(theme_path):
            print(f"主题文件不存在: {theme_path}")
            return None
        
        try:
            file = QFile(theme_path)
            if file.open(QFile.ReadOnly | QFile.Text):
                stream = QTextStream(file)
                stylesheet = stream.readAll()
                file.close()
                self.current_theme = theme_name
                return stylesheet
            else:
                print(f"无法打开主题文件: {theme_path}")
                return None
        except Exception as e:
            print(f"加载主题时出错: {e}")
            return None
    
    def get_current_theme(self):
        """获取当前主题名称"""
        return self.current_theme
    
    def get_available_themes(self):
        """获取可用主题列表"""
        return list(self.themes.keys())
    
    def apply_theme(self, app, theme_name):
        """应用主题到应用程序"""
        stylesheet = self.load_theme(theme_name)
        if stylesheet:
            app.setStyleSheet(stylesheet)
            return True
        return False